from html.parser import HTMLParser

from bs4 import BeautifulSoup
from rest_framework import serializers as rest_serializers

from .models import *


class PartnersSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Partners
        fields = '__all__'


class ProductSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = '__all__'


class NewsListSerializer(rest_serializers.ModelSerializer):
    plain_content = rest_serializers.SerializerMethodField()

    class Meta:
        model = News
        fields = ['id', 'title', 'plain_content', 'publish_date', 'cover_image_url']

    def get_plain_content(self, obj):
        soup = BeautifulSoup(obj.content, 'lxml')
        return soup.get_text()


class NewsSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = News
        fields = '__all__'


class HonourSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Honour
        fields = '__all__'


class SimpleNewsSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = News
        fields = ['id', 'title']


class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)


def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()


class ProjectSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = '__all__'


class NewsListSerializer(rest_serializers.ModelSerializer):
    content = rest_serializers.SerializerMethodField()

    class Meta:
        model = News
        fields = ['id', 'title', 'publish_date', 'cover_image_url', 'content', ]  # 包含您需要的字段

    def get_content(self, obj):
        # 去除 HTML 标签
        stripped_content = strip_tags(obj.content)
        # 限制为 200 个字符
        return stripped_content[:200]
